from logging import getLogger

from fitz import open as pdf_open
from fitz import Page

from ..receipt.type import ReceiptType, get_receipt_type, get_receipt_type_name
from ..receipt.rects import GENERAL_RECEIPT_RECTS, VAT_RECEIPT_RECTS
from ..receipt.handler import GENERAL_RECEIPT_HANDLER, VAT_RECEIPT_HANDLER
from ..receipt.utils import get_block_content_bbox

logger = getLogger(__name__)


def read_receipt_info(page: Page, blocks, receipt_rects, handler) -> dict:
    result = {}

    for key, rect in receipt_rects.items():
        try:
            logger.debug(f"处理发票信息 {key}")
            content = get_block_content_bbox(blocks, rect)
            # content = page.get_textbox(rect)
            result[key] = handler[key](content)
        except Exception as e:
            logger.debug(f"处理发票信息 {key} 时出错: {e}")

    return result


def read_receipt(doc_path: str) -> tuple[ReceiptType, dict]:
    logger.debug(f"处理发票: {doc_path}")

    try:
        with pdf_open(doc_path) as doc:
            type = get_receipt_type(doc)
            logger.debug(f"发票类型: {get_receipt_type_name(type)}")

            page = doc.load_page(0)
            blocks = page.get_text_blocks()

            result = {"filepath": doc_path, "type": get_receipt_type_name(type)}
            match type:
                case ReceiptType.GENERAL_RECEIPT:
                    blocks = blocks[13:-2]
                    result.update(
                        read_receipt_info(
                            page, blocks, GENERAL_RECEIPT_RECTS, GENERAL_RECEIPT_HANDLER
                        )
                    )
                case ReceiptType.VAT_RECEIPT:
                    blocks = blocks[36:]
                    result.update(
                        read_receipt_info(
                            page, blocks, VAT_RECEIPT_RECTS, VAT_RECEIPT_HANDLER
                        )
                    )
                case ReceiptType.UNKNOWN:
                    pass
    except Exception as e:
        logger.error(f"处理发票 {doc_path} 时出错: {e}")
        result = {"filepath": doc_path, "type": f"错误 {e}"}
        type = ReceiptType.UNKNOWN

    return type, result
